package com.aiit.carinsurance2.controller;

import com.aiit.carinsurance2.pojo.Carinsurance;
import com.aiit.carinsurance2.pojo.User;
import com.aiit.carinsurance2.pojo.Userinsurance;
import com.aiit.carinsurance2.service.UserinsuranceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserinsuanceController {
    @Autowired
    private UserinsuranceService userinsuranceService;

    @GetMapping("/look")
    public ModelAndView check() {
        ModelAndView mav = new ModelAndView();
        List<Carinsurance> carinsurances = userinsuranceService.queryAll();
        mav.addObject("carinsurance", carinsurances);
        mav.setViewName("look");
        return mav;
    }

    @PostMapping("/add")
    @ResponseBody
    public int doadd(String id, HttpSession session) {
        Integer coverageid = Integer.parseInt(id);
        Object obj = session.getAttribute("user");
        User u = (User) obj;
        Integer uid = u.getUid();
//        System.out.println(coverageid);
        Integer rlt;
        Userinsurance ui = userinsuranceService.querybyid(coverageid,uid);

//        System.out.println(coverageid);
//        System.out.println(uid);
        if (ui != null) {
            rlt = 2;
        } else {
            rlt = userinsuranceService.insert(coverageid, uid);
        }
//        Integer rlt = 1;
        return rlt;
    }

    @PostMapping("/delete")
    @ResponseBody
    public int dodelete(String id,HttpSession session) {
        Object obj = session.getAttribute("user");
        User u = (User) obj;
        Integer uid = u.getUid();

        Integer coverageid = Integer.parseInt(id);
        int rlt = userinsuranceService.delete(coverageid,uid);
        return rlt;
    }
}

